#!/usr/bin/env python

import sys
import urllib2

urlMap = {
    'curie': ('http://bldwtl07.aqua.mitra.com:8080', '/cruisecontrol/buildresults/agfahc-pacs-services-setup-curie-clean'), 
    'impax62': ('http://10.237.242.234:8080', '/cruisecontrol/buildresults/agfahc-pacs-services-setup-impax62'),
    'main': ('http://bldwtl07.aqua.mitra.com:8080', '/cruisecontrol/buildresults/agfahc-pacs-services-setup-main'),
    'impax63': ('http://bldwtl07.aqua.mitra.com:8080', '/cruisecontrol/buildresults/agfahc-pacs-services-setup-impax63')
    }

def findPreviousBuild(lines, buildNumber ):
    previousBuild = None
    afterLatest = 0
    
    for line in lines:
        if afterLatest == 0:
            if -1 != line.find('Latest Build'):
                afterLatest = 1
        else:
            if -1 != line.find('<tr><td>'):
                afterLatest += 1
                if afterLatest > 2 and -1 != line.find('_build' + buildNumber):

                    hrefIndex = line.find('href="')
                    previousBuild = line[hrefIndex + 6:line.find('"', hrefIndex + 7)]
                    return previousBuild
        
    return previousBuild

def findFailedTests(lines):
    tag = 'class="unittests-data">'
    failedTests = []
    for line in lines:
        index = line.find(tag)
        if -1 != index:
            start = index + len(tag)
            end = line.find('<', start + 1)
            if -1 != end:
                failedTests.append(line[start:end])
    failedTests.sort()
    return failedTests
    

def main(args=None):
    if args == None:
        args = sys.argv[1:]

    previousBuildNumber = ''

    if len(args) > 1:
        previousBuildNumber = args[1]
    
    (hostname, tail) = urlMap[args[0]]
    baseUrl = hostname + tail

    lines = urllib2.urlopen(baseUrl).readlines()
    newFailedTests = findFailedTests(lines)


    previousBuildUrl = findPreviousBuild(lines, previousBuildNumber)

    url = hostname + previousBuildUrl
    
    print 'Comparing last build against ' + url
    oldFailedTests = findFailedTests(urllib2.urlopen(url).readlines())

    scores = {}
    for test in oldFailedTests:
        scores[test] = -1

    for test in newFailedTests:
        scores[test] = scores.get(test, 0) + 1

    fixedTests = [t for t in scores.keys() if scores[t] < 0]
    brokenTests = [t for t in scores.keys() if scores[t] > 0]



    if fixedTests:
        fixedTests.sort()
        print 'Fixed tests:\n ', '\n  '.join(fixedTests)
        print

    if brokenTests:
        brokenTests.sort()
        print 'Broken tests:\n ', '\n  '.join(brokenTests)


    return 0


if __name__ == '__main__':
    sys.exit(main())

